package com.lh.ssm.web;

import com.lh.ssm.domain.Address;
import com.lh.ssm.domain.User;
import com.lh.ssm.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.List;

@Controller
public class AddressController {

    @Autowired
    private AddressService addressService;

    @RequestMapping("/addressShow")//地址管理接口搞定
    public String show(HttpSession session, HttpServletRequest request) {
        //判断用户是否登录
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            session.setAttribute("msg", "请先登录");
            return "login";
        }

        int uid = user.getId();
        List<Address> list = addressService.findAddressByUid(uid);

        //跳转到地址列名页面
        request.setAttribute("list", list);

        return "self_info";

    }

    @PostMapping("/addressAdd")//添加地址搞定
    public String add(String uid,String name,String phone,String detailAddress){

        int result = addressService.addByUser(uid,name,phone,detailAddress);
        return "forward:/addressShow";
    }

    @GetMapping("/addressSetDefault")
    public String setDefault(HttpSession session,String aid){
        //验证用户是否登录
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            session.setAttribute("msg", "请先登录");
            return "/login";
        }

        int uid = user.getId();
        int result = addressService.setAddress(uid,aid);
        return "forward:/addressShow";

    }

    @PostMapping("/addressUpdate")
    public String update(HttpServletRequest request,Address address){
        int result = addressService.updateAddress(address);

        return "forward:/addressShow";
    }

    @GetMapping("/addressDelete")
    public String deleteAddressById(String aid){
        int result = addressService.deleteAddressById(aid);
        return "forward:/addressShow";
    }
}
